﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using DataUpload;
using Logistics.DataManage.DB;
using Logistics.DataManage.Local;
using Logistics.DataManage.Server;
using Logistics.Utils;

namespace Logistics.DataManage
{
    class DataUploader
    {
        private String BackupLocation = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LocalDbBackup");
        private String localDbLocation = ConnectStringMgr.SqliteDbLocation;
        
        public bool UploadWayBills(out String msg)
        {
            msg = "";
            //首先检查服务可用性
            if (!NetworkUtils.IsNetworkConnected())
            {
                throw new Exception("当前网络不可用,请检查网络连接");
            }
            //备份本地数据库
            BackupLocalDataBase(localDbLocation, BackupLocation);

            DataSet DsBills = GetUnUploadLocalBills();
            if (DsBills != null && DsBills.Tables[0].Rows.Count > 0)
            {
                String[] uploadedIds = UpLoadBills(DsBills);
                UploadLogs(uploadedIds);
                SendSMS(uploadedIds);

                int upCount = DsBills.Tables[0].Rows.Count;
                int successCount = uploadedIds == null ? 0 : uploadedIds.Length;
                if (successCount < upCount)
                {
                    msg = (upCount-successCount)+"条运单上传失败";
                    return false;
                }
                return true;
            }
            return false;
        }

        public int GetUnUploadLocalBillCount()
        {
            string str = "select count(*) from WaybillInfo where Isused=1";   //未上传标志位
            Object ocount = LocalDb.Handler.ExecuteScalar(str);
            return Convert.ToInt32(ocount);
        }
        private DataSet GetUnUploadLocalBills()
        {
            string str = "select * from WaybillInfo where Isused=1";   //未上传标志位
            DataSet ds = LocalDb.ExecuteQuery(str);
            return ds;
        }

        private String[] UpLoadBills(DataSet Bills)
        {
            String[] BillIds = RemoteDateServiceFactory.DateService.UploadBills(Bills);
            String ids = "";
            foreach (String id in BillIds)
                ids += "'" + id + "',";
            if (!String.IsNullOrEmpty(ids))
            {
                ids = ids.Substring(0, ids.Length - 1);
                string sql = "Update WaybillInfo set Isused='0' where WayBillId in (" + ids + ")";
                LocalDb.ExecuteNonQuery(sql);
            }
            return BillIds;
        }

        private void UploadLogs(String[] BillIds)
        {
            if (BillIds != null && BillIds.Length > 0)
            {
                string str_ID = "";
                foreach (string str in BillIds)
                    str_ID += "'" + str + "',";
                str_ID = str_ID.TrimEnd(',');
                string sql = "select * from WaybillLog where State=0 and WaybillID in(" + str_ID + ")";
                DataSet ds = LocalDb.ExecuteQuery(sql);
                String[] LogIds = RemoteDateServiceFactory.DateService.UpLoadLogs(ds);
                string updateSQL = "update WaybillLog set State='1' where State=0 and WaybillID in(" + str_ID + ") ";
                LocalDb.ExecuteNonQuery(updateSQL);
            }
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="BillIds"></param>
        /// <returns></returns>
        private String SendSMS(String[] BillIds)
        {
            HttpServiceObject hpService = new HttpServiceObject();
            string rst_msg = hpService.SendSMS(BillIds);
            if (rst_msg.Contains("余额不足"))
            {
                return "短信余额不足";
            }
            return null;
        }

        private void BackupLocalDataBase(String src,String backupDirectory)
        {
            if (!Directory.Exists(backupDirectory))
            {
                Directory.CreateDirectory(backupDirectory);
            }
            String bakupName = "Backup-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".sdf";
            String des = Path.Combine(backupDirectory, bakupName);
            File.Copy(src, des, true);
            DirectoryInfo DirInfo = new DirectoryInfo(backupDirectory);
            DirInfo.Attributes = FileAttributes.Hidden;
            FileInfo[] files = DirInfo.GetFiles();
            files.OrderBy(el => el.CreationTime);//按创建时间升序
            for (int i = 0; i < files.Length-7; i++)
            {
                files[i].Delete();
            }
        }
    }
}
